import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { Express } from 'express';
import * as path from 'path';
import * as fs from 'fs-extra';
import * as moment from 'moment';
import IHelper from '@/services/helper.service';
import IConstants from '@/core/constants';
import IResponse from '@/services/response.service';
import { ConfigService } from '@nestjs/config';
import { ReqProvider } from '@/core/providers/req.provider';
import { delay, map, of } from 'rxjs';
import { RedisProvider } from '@/core/providers/redis.provider';

@Injectable()
export class SharedService {
  constructor(
    private readonly configService: ConfigService,
    private readonly reqProvider: ReqProvider,
    private readonly redisProvider: RedisProvider,
  ) {
    fs.ensureDirSync(path.join(IConstants.publicDir, 'uploads'));
  }

  upload(file: Express.Multer.File) {
    const ALLOW_EXT_LIST: string[] = ['.JPG', '.PNG', '.JPEG', '.MP4'];
    const MAX_SIZE: number = 500 * 1000 * 1000;
    const extname = path.extname(file.originalname);
    if (file.size > MAX_SIZE) {
      throw new HttpException(
        'File size cannot exceed 5M',
        HttpStatus.BAD_REQUEST,
      );
    }
    if (!ALLOW_EXT_LIST.includes(extname.toUpperCase())) {
      throw new HttpException(
        'The extname not supported to upload.',
        HttpStatus.BAD_REQUEST,
      );
    }
    const relativePath = path.join(
      'uploads',
      moment().format('YYYY/MM/DD'),
      `${IHelper.hash(32)}${extname}`,
    );
    const absoluteFilepath = path.join(IConstants.publicDir, relativePath);
    fs.ensureFileSync(absoluteFilepath);
    fs.writeFileSync(absoluteFilepath, file.buffer);
    const url = path.join(
      this.configService.get('STATIC_PREFIX', 'static'),
      relativePath,
    );
    const finalUrl = ['', ...url.split(path.sep)].join('/');
    return of(null).pipe(
      delay(1000),
      map(() => IResponse.success({ url: finalUrl })),
    );
  }

  debug(id: number) {
    return this[`debug${id}`]();
  }
}
